#include "utils/log_manager.h"

#include <boost/filesystem.hpp>
#include <chrono>
#include <ctime>
#include <iomanip>

namespace camera_calibration {

LogManager* LogManager::instance_ = NULL;

LogManager* LogManager::GetInstance() {
  if (instance_ == NULL) {
    instance_ = new LogManager();
  }
  return instance_;
}

void LogManager::Init(std::string _log_root_path, int _retention_days) {
  log_root_path_ = _log_root_path;

  // 检测文件夹是否存在
  if (!boost::filesystem::exists(log_root_path_)) {
    boost::filesystem::create_directories(log_root_path_);
  }

  // 新建当前log文件夹
  auto now = std::time(nullptr);
  auto now_time = std::localtime(&now);
  int cur_mon = now_time->tm_mon + 1;
  int cur_day = now_time->tm_mday;
  char today_buffer[11];
  std::strftime(today_buffer, sizeof(today_buffer), "%Y-%m-%d", now_time);
  std::string time_str(today_buffer);

  current_log_path_ = log_root_path_ + "/" + time_str;
  if (!boost::filesystem::exists(current_log_path_)) {
    boost::filesystem::create_directories(current_log_path_);
  }

  // 计算log保留截止时间
  std::chrono::system_clock::time_point retention_day =
      std::chrono::system_clock::now() -
      std::chrono::hours(24 * _retention_days);
  std::time_t retention_day_time =
      std::chrono::system_clock::to_time_t(retention_day);
  std::tm* retention_local_time = std::localtime(&retention_day_time);

  // 读取文件夹下的所有文件信息,并删除超过截止时间的log文件
  boost::filesystem::path root_path(log_root_path_);
  for (const auto& entry : boost::filesystem::directory_iterator(root_path)) {
    if (boost::filesystem::is_directory(entry)) {
      std::string file_name = entry.path().filename().string();

      std::tm log_time = {};
      std::istringstream ss(file_name);
      ss >> std::get_time(&log_time, "%Y-%m-%d");
      // printf("%i, %i, %i \n ", log_time.tm_year + 1900, log_time.tm_mon + 1,
      //        log_time.tm_mday);

      if (std::difftime(std::mktime(&log_time),
                        std::mktime(retention_local_time)) < 0) {
        boost::filesystem::remove_all(entry.path());
      }
    }
  }
}

std::string LogManager::GetLogPath() { return current_log_path_; }

}  // namespace camera_calibration
